package com.miniprogram.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.miniprogram.bean.po.CustomerUser;
import com.miniprogram.bean.po.CustomerUserToken;
import com.miniprogram.api.mapper.CustomerUserTokenMapper;
import com.miniprogram.api.service.ICustomerUserTokenService;
import com.miniprogram.common.service.BaseServiceImpl;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 用户Token表 服务实现类
 * </p>
 *
 * @author lin
 * @since 2022-06-21
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CustomerUserTokenServiceImpl extends BaseServiceImpl<CustomerUserTokenMapper, CustomerUserToken> implements ICustomerUserTokenService {

    /**
     * 有效期
     */
    private final static Long EXPIRE = 15552000L;


    @Override
    public CustomerUserToken getByToken(String token) {
        QueryWrapper<CustomerUserToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerUserToken::getToken, token);
        return this.getOne(queryWrapper);
    }

    @Override
    public CustomerUserToken getByUserId(Integer userId) {
        QueryWrapper<CustomerUserToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerUserToken::getUserId, userId);
        return this.getOne(queryWrapper);
    }

    /**
     * 登录创建token，如果已经存在则更新
     *
     * @param user 用户实体类
     */
    @Override
    public CustomerUserToken createTokenForLogin(CustomerUser user) {
        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //用户token
        String token;

        //判断是否生成过token
        CustomerUserToken tokenEntity = this.getByUserId(user.getId());
        if (tokenEntity == null) {
            //生成一个token
            token = generateToken();

            tokenEntity = new CustomerUserToken();
            tokenEntity.setUserId(user.getId());
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            tokenEntity.setJsonInfo(new Gson().toJson(user));

            //保存token
            this.save(tokenEntity);
        } else {
//            token = generateToken();
            tokenEntity.setUserId(user.getId());
//            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);
            tokenEntity.setJsonInfo(new Gson().toJson(user));

            //更新token
            this.updateById(tokenEntity);
        }

        return tokenEntity;
    }

    private String generateToken() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
